package com.example.demo;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;

import org.apache.commons.codec.binary.Base64;

/**
 * @author Kent HAN
 * @date 2021/7/13
 */
@SuppressWarnings("restriction")
public class AES {

    static String str;

    public static String encrypt(String raw, String dataSecret, String dataSecretiv) {
        try {
            byte[] dataSecretByteArray = dataSecret.getBytes("UTF-8");
            SecretKeySpec skeySpec = new SecretKeySpec(dataSecretByteArray, "AES");
            IvParameterSpec iv = new IvParameterSpec(dataSecretiv.getBytes());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);

            // 加密
            byte[] encrypted = cipher.doFinal(raw.getBytes("UTF-8"));
            str = new Base64().encodeAsString(encrypted);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return str;
    }

    public static String decrypt(String encryptedStr, String dataSecret, String dataSecretiv){
        try {
            byte[] dataSecretByteArray = dataSecret.getBytes("UTF-8");
            SecretKeySpec skeySpec = new SecretKeySpec(dataSecretByteArray, "AES");
            IvParameterSpec iv = new IvParameterSpec(dataSecretiv.getBytes());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);

            // 解密
            byte[] base64Decoded = new Base64().decode(encryptedStr);
            byte[] decryptedBytes = cipher.doFinal(base64Decoded);
            str = new String(decryptedBytes, "UTF-8");

        } catch (Exception e) {
            e.printStackTrace();
        }
        return str;
    }

    public static void main(String[] args) {
        String kentEncrypted = AES.encrypt("kent", "hehehehehehehehe", "hehehehehehehehe");
        System.out.println(kentEncrypted);

        String kentDecrypted = AES.decrypt("gkuAG4oUY/T4AsC6PTzgrA==", "hehehehehehehehe", "hehehehehehehehe");
        System.out.println(kentDecrypted);
    }

}
